#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from sqlserver.commons.sqlserver_db_model import BaseModel, SqlServerIndex
from common.database.db_session import get_db_instance


class SqlServerIndexFile:
    """
    说明：细粒度索引文件数据库操作接口
        获取会话，进行数据库增、删、改、查操作
    """

    def __init__(self, url):
        self._database = get_db_instance(url)
        self._database.create_table(BaseModel)

    def insert_record(self, sqlserver_index_data: SqlServerIndex):
        with self._database.session_scope() as session:
            session.add(sqlserver_index_data)

    def insert_records(self, records):
        """
        功能： 插入多条索引文件记录
        参数：@records 数据列表
        """
        with self._database.session_scope() as session:
            session.add_all(records)

    def query_by_id(self, uid):
        """
        功能： 查询一个type类型多的数据表
        参数：@uid 资源ID
        """
        with self._database.session_scope() as session:
            return session.query(SqlServerIndex).filter(SqlServerIndex.UUID == uid).first()

    def query_by_conditions(self, backup_type, name=None):
        """
        功能： 查询一个type类型多的数据表
        参数：@backup_type 参见 dws.common.const.BackupResType
             @name：资源名字
        """
        with self._database.session_scope() as session:
            query = session.query(SqlServerIndex).filter(SqlServerIndex.TYPE == backup_type)

            if name:
                query = query.filter(SqlServerIndex.NAME == name).all()
            return query
